using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace zevenseas.Community.Web.UI.WebControls
{
    public class QuickAlert : CompositeControl
    {
        private const string quickAlertKey = "QuickAlert";
        SPWeb currentWeb;
        private Guid AlertID;
        private bool deactivateMode;
        private bool secondRun;
        private LinkButton createAlert;
        private Panel panel;

        private string createAlertText;
        private string deleteAlertText;

        private string listName;
        private SPEventType changeType;
        private SPAlertFrequency alertFrequency;

        public SPEventType ChangeType
        {
            get { return changeType; }
            set { changeType = value; }
        }

        public SPAlertFrequency AlertFrequency
        {
            get { return alertFrequency; }
            set { alertFrequency = value; }
        }

        public string ListName
        {
            get { return listName; }
            set { listName = value; }
        }

        public string CreateAlertText
        {
            get { return createAlertText; }
            set { createAlertText = value; }
        }

        public string DeleteAlertText
        {
            get { return deleteAlertText; }
            set { deleteAlertText = value; }
        }

        protected override void CreateChildControls()
        {
            currentWeb = SPContext.Current.Web;
            SPList alertList = GetAlertList();

            //need to create an exception object for this really.
            if (alertList == null) return;
            if (!alertList.DoesUserHavePermissions(SPBasePermissions.CreateAlerts)) return;

            try
            {
                panel = new Panel();
                panel.CssClass = "zs-quickalert";
                createAlert = new LinkButton();

                //Note: Added SecondRun to overcome an issue where the Alerts collection for a user
                //was not updated when added via the CreateAlert event.
                bool action;
                if (secondRun)
                    action = deactivateMode;
                else
                    action = AlertExists();

                if (action)
                {
                    createAlert.Text = deleteAlertText;
                    createAlert.CssClass = quickAlertKey;
                    createAlert.CommandArgument = "Delete";
                    createAlert.Command += CreateAlert;
                }
                else
                {
                    createAlert.Text = createAlertText;
                    createAlert.CssClass = "rss";
                    createAlert.CommandArgument = "Create";
                    createAlert.Command += CreateAlert;
                }

                panel.Controls.Add(createAlert);
                Controls.Add(panel);
            }
            catch (Exception ex)
            {
                return;
            }

            base.CreateChildControls();
        }

        private SPList GetAlertList()
        {
            try
            {
                SPList alertList = SPContext.Current.Web.Lists[listName];
                return alertList;
            }
            catch (ArgumentException e)
            {
                return null;
                //User does not have access to the list
            }
        }

        private bool AlertExists()
        {
            foreach (SPAlert alert in currentWeb.CurrentUser.Alerts)
            {
                if (alert.Properties.ContainsKey(quickAlertKey))
                {
                    if(alert.Properties[quickAlertKey] == GetUniqueAlertKey())
                    {
                        AlertID = alert.ID;
                        return true;
                    }
                }
            }
            return false;
        }

        private string GetUniqueAlertKey()
        {
            StringBuilder uniqueAlertKey = new StringBuilder();
            uniqueAlertKey.Append(ChangeType.ToString());
            uniqueAlertKey.Append(AlertFrequency.ToString());
            uniqueAlertKey.Append(ListName);

            return uniqueAlertKey.ToString();
        }

        private void CreateAlert(object sender, CommandEventArgs e)
        {
            if (e.CommandArgument.ToString() == "Create")
            {
                SPAlert alert = currentWeb.Alerts.Add();
                alert.User = currentWeb.CurrentUser;
                alert.AlertType = SPAlertType.List;
                alert.List = currentWeb.Lists[ListName];
                alert.EventType = ChangeType;
                alert.AlertFrequency = AlertFrequency;
                alert.Properties.Add(quickAlertKey, GetUniqueAlertKey());
                alert.Properties.Update();
                alert.Update();
                deactivateMode = true;
            }

            if (e.CommandArgument.ToString() == "Delete")
            {
                currentWeb.CurrentUser.Alerts.Delete(AlertID);
                deactivateMode = false;
            }

            secondRun = true;
            Controls.Clear();
            CreateChildControls();
        }
    }
}